package com.kfm.hotel.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;


import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;


public class BaiduUtil {
    /**
     * 获取Access_Token
     */
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    public static String getAccessToken(String clientId,String clientSecret) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+ clientId +"&client_secret="+ clientSecret +"")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = mapper.readValue(response.body().string(), new TypeReference<Map<String, Object>>() {
        });
        return map.get(Constant.ACCESS_TOKEN).toString();
    }


    public static String idcard(byte[] imgData, String accessToken) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        try {
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front" + "&image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。


            String result = HttpUtil.post(url, accessToken, param);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args){
        String celientId="xxx";
        String clientSecret="xxx";
        try{
            String accessToken=getAccessToken(celientId,clientSecret);
            System.out.println(accessToken);
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
}

